import * as Cesium from "cesium";
/* eslint-disable */

// 目前的地图函数，加载了各种图层
export const InitBaseMap = function (dom, setView = true) {
    const baseMapUrl = window.SystemConfig.baseMapUrl;
    const parseUrl = parseGeoserverUrl(baseMapUrl)
    Cesium.Ion.defaultAccessToken = window.SystemConfig.cesiumMapToken
    
    // 加载wms地图
    var baseMap;
    if (baseMapUrl == "") {
        baseMap = new Cesium.UrlTemplateImageryProvider({
            url: "https://webst02.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}",
        });
    }
    else {
        baseMap = new Cesium.WebMapServiceImageryProvider({
            url: `${baseMapUrl}`,
            layers: parseUrl.layers,
            parameters: {
                transparent: true,     //是否透明
                format: 'image/jpeg',
                service: 'WMS',
                srs: 'EPSG:4326',
                styles: '',
                width: 256,
                height: 256,
            }
        });
    }
    
    try {
        var viewer = new Cesium.Viewer(dom, {
            animation: false, //是否创建动画小器件，左下角仪表
            baseLayerPicker: false, //是否显示图层选择器
            fullscreenButton: false, //是否显示全屏按钮
            geocoder: false, //是否显示geocoder小器件，右上角查询按钮
            homeButton: false, //是否显示Home按钮
            infoBox: false, //是否显示信息框
            sceneModePicker: false, //是否显示3D/2D选择器
            selectionIndicator: false, //是否显示选取指示器组件
            timeline: false, //是否显示时间轴
            sceneMode: Cesium.SceneMode.SCENE3D, //设定3维地图的默认场景模式:Cesium.SceneMode.SCENE2D、Cesium.SceneMode.SCENE3D、Cesium.SceneMode.MORPHING
            navigationHelpButton: false, //是否显示右上角的帮助按钮
            scene3DOnly: true, //如果设置为true，则所有几何图形以3D模式绘制以节约GPU资源
            navigationInstructionsInitiallyVisible: false,
            showRenderLoopErrors: true, //显示渲染错误以便调试
            //设置背景透明
            orderIndependentTranslucency: false,
            contextOptions: {
                webgl: {
                    alpha: true,
                    //为了让canvas可以获取Cesium截图
                    preserveDrawingBuffer: true,
                }
            },
            imageryProvider: baseMap,
        });
        
        console.log('Cesium Viewer 初始化成功');
        
        // 添加错误监听
        viewer.scene.globe.imageryLayers.layerAdded.addEventListener(function(layer) {
            console.log('影像图层已添加:', layer);
        });
        
        viewer.scene.globe.imageryLayers.layerShownOrHidden.addEventListener(function(layer, index, show) {
            console.log('影像图层显示状态变化:', layer, '显示:', show);
        });
        
    } catch (error) {
        console.error('Cesium Viewer 初始化失败:', error);
        throw error;
    }
    viewer._cesiumWidget._creditContainer.style.display = "none"; //隐藏图标
    // 去掉默认的双击锁定实体事件和点击事件
    viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
    viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
    viewer._container.style.cursor = "default";
    if (setView) {
        viewer.camera.setView({   //动画需要flyto
            // fromDegrees()方法，将经纬度和高程转换为世界坐标121.503299,31.240609
            destination: Cesium.Cartesian3.fromDegrees(
                ...window.SystemConfig.initialPosition.destination
            ),
            orientation: {
                //   方位角
                heading: 6.283185307179586,
                // 俯仰角
                pitch: -1.5686521559334161,
                //   翻滚角
                roll: 0,
            }
        });
    }
    
    return viewer;
}
// 解析wms的url地址里的query参数
export const queryURLparamsRegEs5 = function (url) {
    let obj = {}
    let reg = /([^?=&]+)=([^?=&]+)/g
    url.replace(reg, function () {
        obj[arguments[1]] = arguments[2]
    })
    return obj
}



// 解析wms的url地址里的query参数
export const parseGeoserverUrl = function (url) {
    let obj = {}
    if (url.indexOf('?') < 0) return obj
    let arr = url.split('?')
    url = arr[1]
    let array = url.split('&')
    for (let i = 0; i < array.length; i++) {
        let arr2 = array[i]
        let arr3 = arr2.split('=')
        obj[arr3[0]] = arr3[1]
    }
    return obj
}

// 笛卡尔坐标转经纬度
export const toLatLng = function (cartesian3) {
    // cesium里面的椭球体默认是wgs84
    let ellipsoid = Cesium.Ellipsoid.WGS84
    // var cartesian3 = new Cesium.Cartesian3(-1374519.2900689477,4901881.004028825,3829373.489589338);
    var cartographic = ellipsoid.cartesianToCartographic(cartesian3);
    var lat = Cesium.Math.toDegrees(cartographic.latitude);
    var lng = Cesium.Math.toDegrees(cartographic.longitude);
    var height = cartographic.height;
    // console.log(lat,lng)
    return {
        "longitude": lng,
        "latitude": lat,
        "altitude": height,
    }
}

// 组合键绘制
export const drawPointCombHandler = function (viewer, callback) {
    var handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
    handler.setInputAction(function (movement) {
        var position, cartographic;
        // 得到射线
        var ray = viewer.scene.camera.getPickRay(movement.position);
        if (ray) {
            // 世界坐标
            position = viewer.scene.globe.pick(ray, viewer.scene);
        }
        if (position) {
            callback(position)
        }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK, Cesium.KeyboardEventModifier.CTRL);
}

/**
 * 绘制函数
 */

// 清空图层
export const clearEntityLayer = function (viewer, layerId) {
    const entityList = viewer.entities.values;
    if (entityList == null || entityList.length < 1) {
        return;
    }
    for (var i = 0; i < entityList.length; i++) {
        var entity = entityList[i];
        if (entity.layerId == layerId) {
            viewer.entities.remove(entity);
            i--;
        }
    }
}
export const addPoint = function (viewer, layerId,latlon,text) {
    const entity = viewer.entities.add({
        layerId: layerId,
        shapeType: "Point",
        position: Cesium.Cartesian3.fromDegrees(...latlon),
        billboard: {
            image: "images/circle_red.png",
            eyeOffset: new Cesium.ConstantProperty(new Cesium.Cartesian3(0, 0, -500)),
            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
          },
        // show: true,
        // pixelSize: 30,
        // heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
        // color: Cesium.Color.RED,
        // outlineColor: Cesium.Color.YELLOW,
        // outlineWidth: 10,
        // scaleByDistance: new Cesium.NearFarScalar(1500, 1, 20000, 0.3),
        // translucencyByDistance: new Cesium.NearFarScalar(1500, 1, 20000, 0.2),
        // distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 20000),
        label:{
            text: text,
            font: '9pt Helvetica',
            pixelOffset : new Cesium.Cartesian2(0, 22)
        }
    });
    return entity
}
// 航线添加地面点
export const addGround = function (viewer, uavId,groundLayerName,position,text) {
    const entity = viewer.entities.add({
        layerId: groundLayerName,
        objId: uavId,
        shapeType: "Point",
        position: position,
        billboard: {
          image: "images/circle_red.png",
          eyeOffset: new Cesium.ConstantProperty(new Cesium.Cartesian3(0, 0, -500)),
          heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
        },
        label: {
          text: text,
          font: '10pt Helvetica',
          fillColor: Cesium.Color.DARKBLUE,
          outlineColor: Cesium.Color.DARKBLUE,
          outlineWidth: 2,
          style: Cesium.LabelStyle.FILL_AND_OUTLINE,
          verticalOrigin: Cesium.VerticalOrigin.TOP,
          pixelOffset: new Cesium.Cartesian2(54, 0)
        }
    });
    return entity
}
// 航线添加空中点
export const addDrone= function (viewer, uavId,uavLayerName,position,text) {
    const entity = viewer.entities.add({
        layerId: uavLayerName,
        objId: uavId,
        shapeType: "Point",
        position: position,
        billboard: {
          image: "images/drone.png",
          eyeOffset: new Cesium.ConstantProperty(new Cesium.Cartesian3(0, 0, -500)),
          //heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
          scale: 0.2,
        },
        label: {
          text: text,
          font: '12pt Helvetica',
          fillColor: Cesium.Color.CRIMSON,
          outlineColor: Cesium.Color.CRIMSON,
          outlineWidth: 2,
          style: Cesium.LabelStyle.FILL_AND_OUTLINE,
          verticalOrigin: Cesium.VerticalOrigin.TOP,
          pixelOffset: new Cesium.Cartesian2(0, 32)
        }
    });
    return entity
}
// 绘制多边形
export const showPolygon = function (viewer,objId, positions,layerId,mcolor='#ff0',height=0) {
    const material = Cesium.Color.fromCssColorString(mcolor).withAlpha(0.5);
    const outlineMaterial = new Cesium.PolylineDashMaterialProperty({
        dashLength: 16,
        color: Cesium.Color.fromCssColorString('#00f').withAlpha(0.7)
    });
    const outlinePositions = [].concat(positions);
    outlinePositions.push(positions[0]);
    const bData = {
        layerId: layerId,
        objId: objId,
        shapeType: "Polygon",
        polyline: {
            positions: outlinePositions,
            clampToGround: true,
            width: 2,
            material: outlineMaterial,
            height : height,
        },
        polygon: new Cesium.PolygonGraphics({
            hierarchy: positions,
            asynchronous: false,
            material: material,
            height : height,
        })
    };
    return viewer.entities.add(bData);
  }
// 闪烁点
export const getFlashColor = function (color) {
    let pointOpacity = 1.0;
    let pointColor2Big = true;
    let pointSize2Big = true;
    let outlineColor2Big = true;
    let outLineOpacity = 1.0;
    let pixelSize = 50;
    let minSize = 20;
    let maxSize = 50;
    let preTime = Cesium.JulianDate.now();
    var preTime1 = Cesium.JulianDate.now();
    var preTime2 = Cesium.JulianDate.now();
    const property = new Cesium.CallbackProperty((time, result) => {
        let timestep = Cesium.JulianDate.secondsDifference(time, preTime);
        if (timestep < 0.1) {
            return color.withAlpha(pointOpacity);
        }
        preTime = time;
        pointOpacity = pointColor2Big ? pointOpacity + 0.1 : pointOpacity - 0.1;
        pointColor2Big = (pointColor2Big && pointOpacity > 0.9) ? false : pointColor2Big;
        pointColor2Big = (!pointColor2Big && pointOpacity < 0.2) ? true : pointColor2Big;
        return color.withAlpha(pointOpacity);
    }, false)
    return  property
}
// 方法定义 lat,lng ,距离单位为km
export const GetDistance = function ( lat1,  lng1,  lat2,  lng2){
    var radLat1 = lat1*Math.PI / 180.0;
    var radLat2 = lat2*Math.PI / 180.0;
    var a = radLat1 - radLat2;
    var  b = lng1*Math.PI / 180.0 - lng2*Math.PI / 180.0;
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
    Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
    s = s *6378.137 ;// EARTH_RADIUS;
    s = Math.round(s * 10000) / 10000;
    return s;
}

export const setView = (viewer, lng, lat) => {
    viewer.camera.setView({   //动画需要flyto
        // fromDegrees()方法，将经纬度和高程转换为世界坐标121.503299,31.240609
        destination: Cesium.Cartesian3.fromDegrees(lng, lat, 2000),
    });
}